import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  Radio,
  Space,
  message,
  Upload,
  Modal,
} from "antd";
import React, { useState, useRef, useEffect } from "react";
import { Link } from "react-router-dom";
import Channel from "components/Channel";

import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import styles from "./index.module.scss";
import { baseURL } from "utils/request";

import { UploadOutlined } from "@ant-design/icons";
import {
  editLishArticleAPI,
  getArticleByIdAPI,
  publishArticleAPI,
} from "api/article";

export default function ArticlePublish(_props) {
  const [fileList, setFileList] = useState([]);
  const [type, setType] = useState(1);

  const draftRef = useRef(false);

  const [imgSrc, setImgSrc] = useState("");
  const props = {
    name: "image",
    accept: ".png,.jpg,.jpeg",
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${localStorage.getItem("geek_pc")}`,
    },
    onChange(info) {
      setFileList(info.fileList);

      if (info.file.status === "done") {
        message.success(`${info.file.name} 上传成功`, 1);
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 上传失败.`, 1);
      }
    },
    onPreview(file) {
      setImgSrc(file.thumbUrl || file.url);
    },
    beforeUpload(file) {
      const imgs = ["image/jpg", "image/png", "image/jpeg"];

      if (!imgs.includes(file.type)) {
        message.warning("不允许上传的文件类型", 1);
        return Upload.LIST_IGNORE;
      }
    },
  };

  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });

  const handleValuesChange = (changedValues, allValue) => {
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };
  const handleFinish = async (values) => {
    if (showFileList.length !== type) {
      return message.warning("图片数量不正确", 1);
    }

    let formData = { ...values };
    formData.cover = {
      type: values.type,
      images: showFileList.map((item) =>
        item.response ? item.response.data.url : item.url
      ),
    };
    delete formData.type;
    //编辑和发布
    if (articleId) {
      await editLishArticleAPI(formData, draftRef.current, articleId);
    } else {
      await publishArticleAPI(formData, draftRef.current);
    }
    message.success("发布成功", 1);
    _props.history.push("/Layout/Content");
  };
  //创建ref控制表单回显数据
  const formRef = useRef({});
  // 编辑传来id;
  const articleId = _props.match.params.id;
  //请求详情
  async function getArticleById() {
    const res = await getArticleByIdAPI(articleId);
    formRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });
    setType(res.data.cover.type);
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  }
  //有id做请求
  useEffect(() => {
    articleId && getArticleById();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div
      style={{
        height: "calc (100vh - 64px)",
        overflow: "auto",
        margin: "20px 0",
      }}
      className={styles.root}
    >
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {`${articleId ? "编辑" : "发布"}`}文章
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          size="large"
          name="basic"
          autoComplete="off"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={handleFinish}
          initialValues={{
            content: "",
            type: 1,
          }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: "请输入文章标题",
              },
            ]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: "请选择频道",
              },
            ]}
          >
            <Channel allowClear></Channel>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                message: "文章内容不能为空",
                validator: (_, value) => {
                  if (value === "<p><br></p>") {
                    return Promise.reject(new Error("内容不能为空"));
                  }
                  return Promise.resolve();
                },
              },
              {
                required: true,
                message: "内容不能为空",
              },
            ]}
          >
            <ReactQuill theme="snow"></ReactQuill>
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={showFileList}>
              {fileList.length < type && <UploadOutlined />}
            </Upload>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                发布文章
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        maskClosable={false}
        title="预览图片"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc("")}
      >
        <img width={480} style={{ objectFit: "cover" }} src={imgSrc} alt="" />
      </Modal>
    </div>
  );
}
